package persistence;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import persistence.exception.DAOException;
import persistence.util.JdbcUtil;

public class RoleDAOJdbcImpl extends JdbcDAOBase implements RoleDAO {

	public RoleDAOJdbcImpl() {
		super();
	}
	@Override
	public Role find(int id) throws DAOException {
		String sql = "SELECT id, rolename FROM roles WHERE id = ?";
		Connection con = null;
		PreparedStatement prepStmt = null;
		ResultSet rs = null;
		Role role = null;
		
		try {
			con = getConProvider().getConnection();
			prepStmt = con.prepareStatement(sql);
			prepStmt.setInt(1, id);
			rs = prepStmt.executeQuery();
			
			if (rs.next()) {
				role = new Role(rs.getInt(1), rs.getString(2));
			}
		}
		catch(SQLException se) {
			throw new DAOException("Problem when attempting to find Role with id: " + id, se);
		}
		finally {
			JdbcUtil.cleanup(con, prepStmt, rs);
		}
		return role;
	}

	@Override
	public List<Role> findAllByName(String roleName) throws DAOException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Role> findAll() throws DAOException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Role> findAllRolesForUser(int userId) throws DAOException {
		String sql = "SELECT r.id, r.rolename FROM user_roles ur"+
					 " INNER JOIN roles r ON ur.roles_id=r.id WHERE ur.users_id = ?";
		Connection con = null;
		PreparedStatement prepStmt = null;
		ResultSet rs = null;
		List<Role> roles = new ArrayList<Role>();
		
		try {
			con = getConProvider().getConnection();
			prepStmt = con.prepareStatement(sql);
			prepStmt.setInt(1, userId);
			rs = prepStmt.executeQuery();
			
			while (rs.next()) {
				roles.add(new Role(rs.getInt(1), rs.getString(2)));
			}
		}
		catch (SQLException se) {
			throw new DAOException("Problem when attempting to find all roles for user with id: " + userId, se);
		}
		finally {
			JdbcUtil.cleanup(con, prepStmt, rs);
		}
		return roles;
	}

	@Override
	public void update(Role role) throws DAOException {
		// TODO Auto-generated method stub

	}

	@Override
	public Role create(int id, String name) throws DAOException {
		// TODO Auto-generated method stub
		return null;
	}

}
